package com.v0710.docommon.tool;

import com.v0710.docommon.exception.SysException;
import com.v0710.docommon.properties.TokenProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Author YIFan
 * @Date 2021-10-30 23:28
 * @Version 1.0
 */
@Component
public class LoginTool {

    private static RedisTool redisTool;
    private static TokenProperties tokenProperties;

    @Autowired
    public void setRedisTool(RedisTool redisTool) {
        LoginTool.redisTool = redisTool;
    }
    public static RedisTool getRedisTool() {
        return redisTool;
    }

    @Autowired
    public void setTokenProperties(TokenProperties tokenProperties) {
        LoginTool.tokenProperties = tokenProperties;
    }
    public static TokenProperties getTokenProperties() {
        return tokenProperties;
    }

    /* 执行登录,获取token*/
    public static String exLogin(Object user){
        String token = getHeaderToken();
        if (userIsLogin(token)) {
            redisTool.set(setTokenKey(token),user,tokenProperties.getExpires());
        }else {
            /* 未登录*/
            token = UUID.randomUUID().toString().replace("-", "");
            redisTool.set(setTokenKey(token),user,tokenProperties.getExpires());
        }
        return token;
    }


    public static Boolean logOut(){
        try {
            String token = getHeaderToken();
            redisTool.del(setTokenKey(token));
            return true;
        } catch (Exception e) {
            throw new SysException("redis remove key error");
        }
    }

    // 用户判断是否存在


    public static String getSessionId(){
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session = attr.getRequest().getSession();
        /*查询该sessionId 是否存在于redis*/
        return session.getId();
    }

    public static String setTokenKey(String token){
//        String md5Str = DigestUtils.md5DigestAsHex((tokenProperties.getToken()+"-"+token).getBytes());
        return tokenProperties.getToken()+":"+token;
    }


    public static Boolean userIsLogin(String token){
        try {
            return redisTool.hasKey(setTokenKey(token));
        } catch (Exception e) {
            return false;
        }
    }

    public static String getHeaderToken(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request.getHeader(tokenProperties.getToken());
    }
}